<template>
  <div class="amap">
    <el-amap
      class="amap-demo"
      ref="map"
      vid="amapDemo"
      :center="center"
      :zoom="zoom"
      :plugin="plugin"
      :events="amapEvents"
      :zooms="zooms"
      :expandZoomRange="true"
      :amap-manager="amapManager"
    >
      <el-amap-marker
        v-for="(marker, index) in pointDataList"
        :position="[marker.location.longitude, marker.location.latitude]"
        :key="marker.order"
        :draggable="isClick"
        :events="markerEvents"
        ref="amapsMarkers"
      >
        <div class="markerImg">{{ marker.order }}</div>
        <!-- 点击删除 -->
        <div class="close-btn" v-if="isClick" @click="deleteMarke(index)">x</div>
      </el-amap-marker>
      <!-- 所有实时无人船 -->
      <el-amap-marker
        v-for="(marker, index) in shipDataList"
        :events="shipMarkerEvents"
        :position="[marker.longitude,marker.latitude]"
      >
        <div class="ship-view-marker">
          <img src="@/assets/img/ship-view/ship.png" alt />
        </div>
      </el-amap-marker>
      <el-amap-polyline
        :path="path"
        stype="dashed"
        strokeColor="#26bef0"
        strokeStyle="dashed"
        strokeWeight="2"
        :events="polylineEvents"
        editable="true"
        :zIndex="polylineZIndex"
      ></el-amap-polyline>
      <!-- 绘制轨迹用 -->
      <el-amap-polyline
        :path="routerTrackLine"
        stype="solid"
        strokeColor="#999"
        strokeStyle="solid"
        strokeWeight="1"
        :events="polylineEvents"
        editable="true"
      ></el-amap-polyline>
      <el-amap-polyline
        :path="routerTrackLineTwo"
        stype="solid"
        strokeColor="#000"
        strokeStyle="solid"
        strokeWeight="4"
        :events="polylineEvents"
        editable="true"
      ></el-amap-polyline>
      <!-- 连接线 -->
      <el-amap-polyline
        :path="targetDistance"
        stype="solid"
        strokeColor="#FF00FF"
        strokeStyle="solid"
        strokeWeight="2"
        v-if="targetDistance && targetDistance[0]"
      ></el-amap-polyline>
      <!-- 实时无人船 -->
      <el-amap-marker
        :events="shipMarkerEvents"
        :position="shipRealTimeLocation"
        v-if="routerTrackLine && routerTrackLine.length != 0"
      >
        <div class="ship-view-marker">
          <img src="@/assets/img/ship-view/ship.png" alt />
        </div>
      </el-amap-marker>
    </el-amap>
    <el-button
      type="primary"
      icon="el-icon-aim"
      @click="satelliteLayer()"
      class="toglerView"
      ref="amapLayer"
    >卫星</el-button>
    <!-- <el-button v-show="isSate" type="primary" icon="el-icon-s-order" @click="satelliteLayer()" class="toglerView" ref="amapLayer">路线</el-button> -->
    <el-button
      type="primary"
      icon="el-icon-map-location"
      @click="clickMapCenter"
      class="toglerView-location"
      v-show="routerTrackLine && routerTrackLine.length != 0"
      ref="usvTrackBtn"
    >船只跟踪</el-button>
  </div>
</template>
<script>
// import '@/plugins/amap';
import Vue from 'vue';
import VueAMap from 'vue-amap';
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap';
import { log } from 'util';
import LoginVue from '../views/login/Login.vue';
Vue.use(VueAMap);

let amapManager = new VueAMap.AMapManager();

export default {
  name: 'Amap',
  data() {
    // 用于在定制中将this指向data
    let self = this;
    return {
      amapManager,
      center: [106.587556, 29.567932],
      zoom: 18,
      zooms: [2, 20],
      // 经纬度暂存
      lanlat: {},
      // 区域中心点
      addressCenter: [],
      dels: new Set(),
      path: [],
      polylineZIndex: 100,
      // 方位角绘制
      reotate: null,
      oldRotate: '',
      // 判断是否是卫星视图
      sateLayer: null,
      isSate: false,
      // 实时无人船位置
      shipRealTimeLocation: [],
      isAutoTrack: false,
      // 高德地图原生使用
      VueMap: null,
      isCompleted: false,
      completedCallbacks: [],
      // ================高德地图方法===================
      // ==========amap方法开始=======
      amapEvents: {
        // 将原生地图暴露出去
        init(o) {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.VueMap = amapManager._map;
            self.sateLayer = new AMap.TileLayer.Satellite();
            for (let cb of self.completedCallbacks) {
              cb(self);
            }
            self.isCompleted = true;
          });
        },
        // 点击地图获取点击经纬度
        click: e => {
          if (this.isClick) {
            // 获取经纬度
            const lnglat = this.getLngLat(e);
            // 更新经纬度
            this.lanlat = lnglat;
            // 回调父级方法
            this.$emit('LngLat', lnglat);
          }
        }
      },
      // ===========amap方法结束===========
      // ===========地图点标记方法==========
      markerEvents: {
        // 鼠标拖动修改对应的经纬度
        dragging: e => {
          // 只获取点击的数字内容，作为下标
          this.pointDataList.splice(parseInt(e.target.Ce.contentDom.querySelector('.markerImg').innerHTML) - 1, 1, {
            location: { latitude: e.lnglat.lat, longitude: e.lnglat.lng },
            order: parseInt(e.target.Ce.contentDom.querySelector('.markerImg').innerHTML)
          });
          // 获取经纬度,用来显示
          const lnglat = this.getLngLat(e);
          this.$emit('ViewLocation', lnglat);
        },
        // 点击可以查看经纬度
        click: e => {
          // 获取经纬度,用来显示
          const lnglat = this.getLngLat(e);
          this.$emit('ViewLocation', lnglat);
        }
      },
      // ===========地图点标记方法结束==========
      // =============折线方法开始========
      polylineEvents: {
        click: e => {
          if (this.isClick) {
            // 获取经纬度
            const lnglat = this.getLngLat(e);
            // 更新经纬度
            this.lanlat = lnglat;
            // 回调父级方法
            this.$emit('LngLat', lnglat);
          }
        }
      },
      // =============折线方法结束==========
      // ============无人船图标方法===========
      shipMarkerEvents: {
        click: e => {
          console.log(e);
          console.log('高德地图方法使用');
        }
      },
      // ============无人船方法结束============
      // ============高德地图方法结束=====================
      // ==插件==
      plugin: [
        // 缩小放大
        {
          pName: 'ToolBar',
          events: {
            init(instance) { }
          }
        }
        // {
        //   pName: 'MapType',
        //   defaultType: 0,
        //   events: {
        //     init(instance) {
        //     },
        //   }
        // }
      ]
    };
  },
  props: {
    //通过plan获取的点,渲染到地图上
    pointDataList: {
      type: Array
    },
    // 地图上显示的所有船只
    shipDataList: {
      type: Array
    },
    // 通过监听判断用户是否点击了绘制点按钮,没有点击不能标记点
    isClick: {
      type: Boolean,
      default: false
    },
    // 绘制轨迹的二维数组
    routerTrackLine: {
      type: Array
    },
    // 第二条轨迹
    routerTrackLineTwo: {
      type: Array
    },
    // 绘制下一站的轨迹
    targetDistance: {
      type: Array
    },
    // 无人船单独信息
    setmanned: {
      type: Object
    }
  },

  methods: {
    // 点击设置经纬度
    getLngLat(e) {
      return {
        latitude: e.lnglat.getLat(),
        longitude: e.lnglat.getLng(),
        value: e.lnglat.getLat() + ',' + e.lnglat.getLng()
      };
    },
    // 在地图执行成功后才会去执行，没有成功将函数保存在数组中，等待地图成功后执行数组中的函数
    onCompleted(cb) {
      if (this.isCompleted) {
        cb();
      } else {
        this.completedCallbacks.push(cb);
      }
    },
    // 新的删除标记
    deleteMarke(val) {
      this.$confirm('即将删除' + (val + 1) + '号标记，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.pointDataList.splice(val, 1);
          // 重新设置order值，传输回去
          for (let i in this.pointDataList) {
            this.pointDataList[i].order = Number(i) + 1;
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 根据地址编码获取经纬度
    getMapCenter(address) {
      let geocoder = new AMap.Geocoder();
      geocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.info == 'OK') {
          this.addressCenter = result.geocodes[0].location;
          // 重设中心点
          this.center = [this.addressCenter.lng, this.addressCenter.lat];
        } else {
          alert(`查询区域${address}失败,请检查输入区域是否正确`);
        }
      });
    },
    // 地图标点自适应
    setView(path) {
      this.$nextTick()
        .then(() => {
          // 高德根据指定坐标进行 地图自适应 ，绘制折线覆盖物，但是覆盖物不显示
          if (path) {
            if (this.shipDataList) {
              this.VueMap.setFitView();
            }
            else {
              this.VueMap.setFitView(new AMap.Polyline({ path: path }));
            }
          } else {
            this.VueMap.setFitView(new AMap.Polyline({ path: this.path }));
          }
        })
        .catch(err => {
          console.log('进入到catch');
          console.log(err);
          this.zoom = 10;
          this.center = [
            this.pointDataList[this.pointDataList.length - 1].location.longitude,
            this.pointDataList[this.pointDataList.length - 1].location.latitude
          ];
          this.$message.error('地图报错，请联系管理员进行修改');
        });
    },
    // 自动跟踪船只位置
    setMapCenter() {
      if (this.setmanned && this.isAutoTrack) {
        this.center = [this.setmanned.location.longitude, this.setmanned.location.latitude];
      }
    },
    // 地图中心点实时跟踪
    clickMapCenter() {
      this.isAutoTrack = !this.isAutoTrack;
      this.$refs.usvTrackBtn.$el.innerHTML = '<i class="el-icon-s-help"></i><span>取消跟踪</span>';
      if (!this.isAutoTrack) {
        this.$refs.usvTrackBtn.$el.innerHTML = '<i class="el-icon-map-location"></i><span>船只跟踪</span>';
        // this.onCompleted(x => this.setView());
      }
    },
    // 根据获取的船信息进行图像操作
    usvTransform() {
      let ship = document.querySelector('.ship-view-marker');
      if (this.setmanned && ship) {
        // 当方位角小于0
        if (this.setmanned.yaw < 0) {
          this.reotate = 360 + this.setmanned.yaw;
        } else {
          this.reotate = this.setmanned.yaw;
        }
        // 当这是第一次获取方位角时
        if (this.oldRotate === '' && ship) {
          this.oldRotate = Math.abs(this.reotate);
          ship.style.transform = `rotate(${this.reotate}deg)`;
          return;
        }
        // 判断船体方位角旋转方式 （差值小于180 顺时针，大于180逆时针）
        if (Math.abs(this.oldRotate - this.reotate) > 180) {
          if (this.reotate <= 180) {
            this.reotate = 360 + this.reotate;
          } else {
            this.reotate = this.reotate - 360;
          }
        }
        // 绘制船体方位角
        if (ship) {
          ship.style.transition = 'transform 0.2s linear';
          ship.style.transform = `rotate(${this.reotate}deg)`;
        }
        //修改方位角的值，固定子360以内
        if (this.reotate > 360) {
          this.oldRotate = this.reotate % 360;
          let deg = this.oldRotate;
          setTimeout(() => {
            ship.style.transition = 'none';
            ship.style.transform = `rotate(${deg}deg)`;
          }, 100);
        } else if (this.reotate < 0) {
          this.oldRotate = this.reotate + 360;
          let deg = this.oldRotate;
          setTimeout(() => {
            ship.style.transition = 'none';
            ship.style.transform = `rotate(${deg}deg)`;
          }, 100);
        } else {
          this.oldRotate = this.reotate;
        }
      }
    },
    // 获取地图 执行相应计划
    async getVueAmap(callback) {
      // 地图开始回调执行，直到获取到 this.vueAmap
      if (!this.VueMap) {
        await setTimeout(() => {
          this.VueMap = amapManager._map;
          this.getVueAmap(callback);
        }, 200);
      } else {
        this.sateLayer = new AMap.TileLayer.Satellite();
        callback();
      }
    },
    // 设置卫星图层
    satelliteLayer() {
      if (this.VueMap) {
        this.isSate = !this.isSate;
        console.log(this.isSate);
        if (this.isSate) {
          this.VueMap.add(this.sateLayer);
          this.$refs.amapLayer.$el.innerHTML = '<i class="el-icon-s-order"></i><span>路线</span>';
        } else {
          this.VueMap.remove(this.sateLayer);
          this.$refs.amapLayer.$el.innerHTML = '<i class="el-icon-aim"></i><span>卫星</span>';
        }
      } else {
        this.$message.error('网速较慢，地图未获取到，请稍后再试');
      }
    }
  },
  created() { },
  components: {},
  computed: {},
  beforeMount() { },
  destroyed() {
    this.completedCallbacks = [];
  },
  mounted() { },
  watch: {
    pointDataList: {
      // 每次修改地图，则重新获取折线路径
      handler() {
        this.path = [];
        for (let line of this.pointDataList) {
          this.$set(this.path, this.path.length, [line.location.longitude, line.location.latitude]);
        }
      },
      deep: true,
      // immediate: true
    },
    // 轨迹变换，中心点始终处于最后
    routerTrackLine: {
      handler() {
        if (this.routerTrackLine) {
          this.setMapCenter();
          if (this.setmanned) {
            this.shipRealTimeLocation = [this.setmanned.calibratedLocation.longitude, this.setmanned.calibratedLocation.latitude];
          }
          this.usvTransform();
        }
      },
      deep: true,
      immediate: true
    }
  }
};
</script>
<style lang="less" scoped>
.amap {
  width: 100%;
  height: 100%;
  position: relative;
}
.markerImg {
  width: 20px;
  height: 32px;
  text-align: center;
  color: #fff;
  background: url('../assets/img/login/mark.png') no-repeat center center/100% 100%;
  position: relative;
  .close-btn {
    position: absolute;
    top: 100%;
    left: 0;
  }
}
.close-btn {
  width: 14px;
  line-height: 14px;
  text-align: center;
  border-radius: 50%;
  background-color: rgba(200, 200, 200, 0.5);
  position: absolute;
  right: -7px;
  top: -7px;
  color: #ff6700;
}
.close-btn:hover {
  background-color: rgba(200, 200, 200, 1);
  color: red;
}
.ship-view-marker {
  height: 60px;
  position: absolute;
  top: 0;
  left: 0px;
  // transform: translate(-50%);

  img {
    height: 100%;
    vertical-align: middle;
  }
}
.toglerView {
  z-index: 500;
  position: absolute;
  bottom: 10px;
  right: 10px;
}
.toglerView-location {
  z-index: 500;
  position: absolute;
  bottom: 48px;
  right: 10px;
}
/deep/.amap-controls > .amap-maptypecontrol {
  position: absolute;
  right: 10px;
  top: calc(100% - 70px);
}
// 隐藏路况图层
/deep/.amap-maptype-list {
  display: none !important;
}
</style>
